package top.anydata.lifeofcode.lifesystem.service.third.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.anydata.lifeofcode.lifesystem.conf.AliYunConf;
import top.anydata.lifeofcode.lifesystem.service.third.IAliYunService;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Date;
import java.util.Map;

/**
 * 功能描述:
 *
 * @author <a href="mailto:caingao@anydata.top">CainGao</a>
 * @version V_1.0
 * @date 2023/10/10 3:19 PM
 */
@Slf4j
@Service
public class AliYunServiceImpl implements IAliYunService {

    @Autowired
    AliYunConf aliYunConf;

    @Override
    public String ossUploadFile(String objectName, MultipartFile file) throws Exception {
        OSS ossClient = new OSSClientBuilder().build(
                aliYunConf.endpoint,
                aliYunConf.ak,
                aliYunConf.sk);
        try {
            PutObjectResult putObjectResult = ossClient.putObject(aliYunConf.bucket,
                    objectName,
                    new ByteArrayInputStream(file.getBytes()));
            return putObjectResult.getResponse().getUri();
        } catch (OSSException e) {
            log.warn("OSS链接错误", e);
            throw e;
        } catch (Exception e) {
            log.warn("", e);
            throw e;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public String ossPresignedUrl(String objectName) {
        OSS ossClient = new OSSClientBuilder().build(
                aliYunConf.endpoint,
                aliYunConf.ak,
                aliYunConf.sk);
        try {
            Date expiration = new Date(new Date().getTime() + 3600 * 1000);
            // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
            URL url = ossClient.generatePresignedUrl(aliYunConf.bucket, objectName, expiration);
            return url.toExternalForm();
        } catch (OSSException e) {
            log.warn("OSS链接错误", e);
        } catch (Exception e) {
            log.warn("", e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    @Override
    public String shortMsgSend(String signName, String phone, String templateCode, Map<String, String> templateParam) {
        return null;
    }
}
